package com.bangdao.app.jetpacktest.jetpack.viewmodel;

import androidx.lifecycle.ViewModel;

import java.util.Timer;
import java.util.TimerTask;

/**
 * @ProjectName: JetpackTest
 * @ClassName: TimerViewModel
 * @Description: java类作用描述
 * @Author: luhui
 * @Email: hui.lu@bangdao-tech.com
 * @CreateDate: 2022/6/3 23:09
 * @UpdateUser: luhui
 * @UpdateDate: 2022/6/3 23:09
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */
public class TimerViewModel extends ViewModel {

    private Timer timer;
    private int currentSecond;

    /**
     * 开始计时
     */
    public void startTiming(){
        if(timer == null){
            currentSecond = 0;
            timer = new Timer();
            TimerTask timerTask = new TimerTask() {
                @Override
                public void run() {
                    currentSecond++;
                    if(onTimeChangeListener != null){
                        onTimeChangeListener.onTimeChanged(currentSecond);
                    }
                }
            };
            timer.schedule(timerTask, 1000, 1000);
        }
    }

    /**
     * 通过接口的方式，完成对调用者的通知
     * 实际上这种方式不是很好，如果要观察的数据很多，则需要定义大量的接口口，代码会显得十分冗余。
     * 更好的方式是通过LiveData组件来实现
     */
    public interface OnTimeChangeListener{
        void onTimeChanged(int second);
    }

    private OnTimeChangeListener onTimeChangeListener;

    public void setOnTimeChangeListener(OnTimeChangeListener onTimeChangeListener){
        this.onTimeChangeListener = onTimeChangeListener;
    }

    /**
     * 清理资源
     */
    @Override
    protected void onCleared() {
        super.onCleared();
        timer.cancel();
    }
}
